package net.qanar.gwnewsfeed.feed.swing;

import java.awt.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

import net.qanar.gwnewsfeed.*;
import net.qanar.gwnewsfeed.feed.Feed;
import net.qanar.gwnewsfeed.reader.IGUReader;

public class StandardGUI extends JPanel implements ListSelectionListener, HyperlinkListener{
	static final long serialVersionUID = 123456789;
	
	private JList listTitles;
	private JScrollPane scrollPane1;
	private ItemPanel ip;
	private java.util.List <Item> items;
	
	public StandardGUI(java.util.List<Item> items) {
		this.setMaximumSize(new Dimension(750,525));
		this.setLayout(new FlowLayout (FlowLayout.LEFT, 5, 5));
		this.items = items;
		Vector<String> titles = new Vector<String>();
		for (Item i : items) {
			titles.add(i.getTitle());
		}
		
		JPanel p = new JPanel();
		p.setPreferredSize(new Dimension(275,525));
		
		listTitles = new JList(titles);
		listTitles.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listTitles.addListSelectionListener(this);
		scrollPane1 = new JScrollPane(listTitles);
		scrollPane1.setPreferredSize(new Dimension(265,320));
		p.add(scrollPane1);
		
		JTextPane jtp = new JTextPane();
		jtp.setContentType("text/html");
		jtp.setText(((Item)new IGUReader().getItems().toArray()[0]).getContent());
		jtp.setEditable(false);
		jtp.setCaret(new QuietCaret());
		jtp.addHyperlinkListener(this);
		JScrollPane jsp = new JScrollPane(jtp);
		jsp.setPreferredSize(new Dimension(265,195));
		p.add(jsp);
		this.add(p);
		
		if (items.size() != 0) {
			ip = new ItemPanel((Item)items.toArray()[0]);
			
		}
		else {
			ip = new ItemPanel();
		}
		this.add(ip);
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		if (listTitles.getSelectedIndex() != -1) {
			ip.update((Item)items.toArray()[listTitles.getSelectedIndex()]);
        }
	}
	@Override
	public void hyperlinkUpdate(HyperlinkEvent arg0) {
		if (arg0.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
			if (arg0.getURL() != null)
				Feed.startBrowser(arg0.getURL());
			else {
				if (arg0.getDescription().charAt(0) == '/') {
					try {
						Feed.startBrowser(new URL("http://www.guildwars.com" + arg0.getDescription()));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}				
		}
	}
}